<?php

namespace addons\hlapp\service;

use addons\hlapp\controller\FileCache;
use addons\hlapp\dto\Result;
use addons\hlapp\dto\WXResult;
use addons\hlapp\model\HlappEvaluateSendLogs;
use addons\hlapp\model\HlappMember;
use addons\hlapp\model\HlappPart;
use addons\hlapp\model\HlappProject;
use addons\hlapp\model\HlappProjectEvaluate;
use addons\hlapp\model\HlappProjectSolve;
use addons\hlapp\util\HttpUtil;
use think\facade\Session;

class PushService
{

    // 工作进展提醒模板
    public static $TEMPLATE_ID = "C9_m3X7GSSY9lT8VbhWmbBmRvc_uLpjpJZRcaVRq7gU";


    //方案反馈给甲方 todo 添加跳转页面
    public function sendSolve2A($solveId){
        $result = Result::getResultError();
        //--跳转url
        $jumpUrl = addonUrl("hlapp/Wap/evaSolvePage",'',true,true);
        $jumpUrl = $jumpUrl."?solveId=".$solveId;
        try{
            $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
            $data=[
                "first"=>["value"=>$solveInfo["pname"],"color"=>"#DC2C26"],
                "keyword1"=>["value"=>"评价方案反馈","color"=>"#173177"],
                "keyword2"=>["value"=>"已对您的评价做出反馈","color"=>"#173177"],
                "keyword3"=>["value"=>$solveInfo['partName'],"color"=>"#173177"],
                "remark"=>["value"=>"点击对方案进行评价","color"=>"#173177"]
            ];
            \Log::INFO("开始推送甲方反馈信息。。");
            $res = $this->sendTemplateMessage($solveInfo['openId'],self::$TEMPLATE_ID,$jumpUrl,$data);
            \Log::INFO("推送甲方负责人返回信息:".json_encode($res));
            if ($res->code){
                //成功
                $result = Result::getResultOk();
            }else{
                $result->setMessage($res->message);
                \Log::ERROR($res->message);
            }
        }catch (\Exception $e){
            $result->setMessage($e->getMessage());
            \Log::ERROR($e->getMessage());
        }
        return $result;
    }


    /**
     * 解决方案推送给总部工程中心
     * @param $solveId  解决方案id
     * @param $sendMemberId  推送人id
     * @return Result
     */
    public function sendSolveToEngineer($solveId,$openId){
        $result = Result::getResultError();
        //--审核url
        $jumpUrl=addonUrl("hlapp/Wap/examSolve",'',true,true);
        $jumpUrl = $jumpUrl."?solveId=".$solveId;
        \Log::INFO("the jumpUrl is:".$jumpUrl);
        try{
            $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
            $data=[
                "first"=>["value"=>"项目名称：".$solveInfo['pname'],"color"=>"#173177"],
                "keyword1"=>["value"=>"不满意评价反馈","color"=>"#173177"],
                "keyword2"=>["value"=>"第".$solveInfo['week']."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>$solveInfo['memberName']."(".$solveInfo['partName'].")","color"=>"#173177"],
                "remark"=>["value"=>"点击对反馈进行审核","color"=>"#173177"]
            ];
            $result = $this->sendTemplateMessage($openId,self::$TEMPLATE_ID,$jumpUrl,$data);
            //保存推送失败日志
            if (!$result->code){
                $log = new HlappEvaluateSendLogs;
                $log['type'] = 3;
                $log['status'] = 0;
                $log['eId'] = $solveId;
                $log['member'] = $solveInfo['mId'];
                $log['message'] = $result->message;
                $log->save();
            }
        }catch (\Exception $e){
            $result->setMessage($e->getMessage());
            \Log::ERROR($e->getMessage());
        }
        return $result;
    }

    /**
     * 未给出方案，警告推送给总部工程中心
     * @param $solveId  解决方案id
     * @return Result
     */
    public function sendWrongEngineer($eId){
        $result = Result::getResultError();
        $jumpUrl = "";
        try{
            $evaluate = HlappProjectEvaluate::get($eId);
            $project = (new HlappProject())->where("id",$evaluate["projectId"])->find();
            //工程中心负责人
            $members = (new HlappMember())->where('partId',HlappPart::$ENGINEERING)->select();
            $data=[
                "first"=>["value"=>"项目名称：".$project['name'],"color"=>"#173177"],
                "keyword1"=>["value"=>"地方负责人未在24小时内给出解决措施","color"=>"#DC2C26"],
                "keyword2"=>["value"=>"第".$evaluate['week']."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>'系统汇报',"color"=>"#173177"],
                "remark"=>["value"=>"未及时反馈警告","color"=>"#173177"]
            ];
            foreach ($members as $member){
                $result = $this->sendTemplateMessage($member['openId'],self::$TEMPLATE_ID,$jumpUrl,$data);
                //保存推送失败日志
                if (!$result->code){
                    $log = new HlappEvaluateSendLogs();
                    $log['type'] = 5;//方案警告推送
                    $log['status'] = 0;
                    $log['eId'] = $evaluate['id'];
                    $log['member'] = $member['id'];
                    $log['message'] = $result->message;
                    $log->save();
                }
            }
        }catch (\Exception $e){
            $result->setMessage($e->getMessage());
            \Log::ERROR($e->getMessage());
        }
        return $result;
    }

    /**
     * 审核失败，打回给方案解决人
     */
    public function sendSolveBack($solveId){
        $result = Result::getResultError();
        //--审核url
        $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
        $jumpUrl=addonUrl("hlapp/Wap/solvePage",'',true,true);
        $jumpUrl = $jumpUrl."?eid=".$solveInfo['eId']."&memberId=".$solveInfo['mId']."&partType=".$solveInfo['partId'];
        \Log::INFO("the jumpUrl is:".$jumpUrl);
        try{
            $data=[
                "first"=>["value"=>"项目名称：".$solveInfo["pname"],"color"=>"#173177"],
                "keyword1"=>["value"=>"工程中心驳回了您的反馈","color"=>"#DC2C26"],
                "keyword2"=>["value"=>"第".$solveInfo['week']."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>$solveInfo['memberName']."(".$solveInfo['partName'].")","color"=>"#173177"],
                "remark"=>["value"=>"点击对反馈重新提交","color"=>"#173177"]
            ];
            $result = $this->sendTemplateMessage($solveInfo['mopenId'],self::$TEMPLATE_ID,$jumpUrl,$data);
            //记录推送失败日志
            if (!$result->code){
                $log = new HlappEvaluateSendLogs();
                $log['type'] = 4;
                $log['status'] = 0;
                $log['eId'] = $solveId;
                $log['member'] = $solveInfo["mId"];
                $log['message'] = $result->message;
                $log->save();
            }
        }catch (\Exception $e){
            $result->setMessage($e->getMessage());
            \Log::ERROR($e->getMessage());
        }
        return $result;
    }

    //甲方对反馈不满意，信息返回给措施提出人
    public function sendUnHappyToSolve($solveId){
        $result = Result::getResultError();
        //--审核url
        $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
        $jumpUrl=addonUrl("hlapp/Wap/evaSolveInfo",'',true,true);
        $jumpUrl = $jumpUrl."?solveId=".$solveId;
        \Log::INFO("the jumpUrl is:".$jumpUrl);
        try{
            $data=[
                "first"=>["value"=>"项目名称：".$solveInfo["pname"],"color"=>"#173177"],
                "keyword1"=>["value"=>"甲方不满意您的反馈","color"=>"#DC2C26"],
                "keyword2"=>["value"=>"第".$solveInfo['week']."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>$solveInfo['memberName']."(".$solveInfo['partName'].")","color"=>"#173177"],
                "remark"=>["value"=>"点击查看详情","color"=>"#173177"]
            ];
            $result = $this->sendTemplateMessage($solveInfo['mopenId'],self::$TEMPLATE_ID,$jumpUrl,$data);
            //记录推送失败日志
            if (!$result->code){
                $log = new HlappEvaluateSendLogs();
                $log['type'] = 4;
                $log['status'] = 0;
                $log['eId'] = $solveId;
                $log['member'] = $solveInfo["mId"];
                $log['message'] = $result->message;
                $log->save();
            }
        }catch (\Exception $e){
            $result->setMessage($e->getMessage());
            \Log::ERROR($e->getMessage());
        }
        return $result;
    }

    //推送日志记录
    public function saveLogs(){
        //todo 记录日志方法
//        $log['projectId']=$projectId;
//        $log['week']=$week;
//        $log['stage']=$project['stage'];
//        $log['member']=$memberId;
//        $log['type']=2;
//        $log['eId']=$eId;
//        $log['part']=$partType;
//        $log['status'] = 0;
    }


    /**
     * 发送模板消息
     * @param $open_id  用户公众号的openId
     * @param $template_id  模板id
     * @param $jumpUrl  消息跳转的url
     * @param $data 模板消息内容
     * @return mixed    返回参数
     */
    public function sendTemplateMessage($open_id,$template_id,$jumpUrl,$data){
        $token = self::getAccessToken();
        $postUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
        //设置发送的消息
        $message = [
            'touser'=>$open_id,
            'template_id'=>$template_id,
            'url'=>$jumpUrl,
            'data'=>$data
        ];
        $data = json_encode($message);
        // 发送
        $res = HttpUtil::actionCurlRequest($postUrl,$data);
        if (!$res){
            //返回结果不存在
            \Log::ERROR("发送模板消息失败，返回参数为空");
            return Result::getResultError();
        }
        if ($res->errcode==0){
            $result = Result::getResultOk();
        }else{
            $result = Result::getResultError();
            $errcode = $res->errcode;
            $result->result = $errcode;
            $result->message =  WXResult::getMessage($errcode);
            \Log::ERROR($result->message);
        }
        return $result;
    }

    //获取 access_token
    public function getAccessToken(){
        $mp_options = Session::get("mp_options");
        $appid = $mp_options["appid"];

        // 查看缓存中是否有数据
        $cache = new FileCache();
        $access_token = $cache->get("access_token_".$appid);
        if(!$access_token){
            $appsecret = $mp_options["appsecret"];
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
            $res = HttpUtil::actionCurlRequest($url);
            \Log::INFO("请求返回数据为:".json_encode($res));
            $access_token = $res->access_token;
            //时间默认5分钟
            $cache->set("access_token_".$appid,$access_token,300);
        }
        return $access_token;
    }
}